import { z } from "zod";
import { CodeIndexOrchestrator } from "../services/orchestrator.js";

export const indexCodebaseSchema = z.object({
  directory: z.string().describe("Absolute path to the codebase directory to index"),
  verbose: z.boolean().default(false).describe("Enable verbose output showing detailed progress"),
});

export type IndexCodebaseArgs = z.infer<typeof indexCodebaseSchema>;

export async function indexCodebaseTool(
  args: IndexCodebaseArgs,
  orchestrator: CodeIndexOrchestrator
): Promise<string> {
  try {
    console.log(`Starting indexing for directory: ${args.directory}`);
    if (args.verbose) {
      console.log(`Verbose mode enabled - detailed progress will be shown`);
    }
    
    await orchestrator.startIndexing(args.directory, args.verbose);
    
    const status = orchestrator.getStatus();
    if (status.stats) {
      return `✅ Successfully indexed codebase at ${args.directory}

**Indexing Results:**
- Files processed: ${status.stats.processed}
- Files skipped: ${status.stats.skipped}
- Code blocks indexed: ${status.stats.totalBlocks}
- Errors: ${status.stats.errors}

The codebase is now ready for semantic search.`;
    } else {
      return `✅ Indexing completed for ${args.directory}. The codebase is ready for search.`;
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    return `❌ Failed to index codebase: ${errorMessage}

Please check:
1. The directory path exists and is accessible
2. You have read permissions for the directory
3. The embedding service is properly configured
4. The vector database (Qdrant) is running and accessible`;
  }
}
